package reader.contorller.manager;

import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reader.entity.Book;
import reader.service.BookService;
import reader.utils.ResponseUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/m/book")
public class MBookController {
    @Autowired
    private BookService bookService;

    @GetMapping("/list")
    public ResponseUtils list(@RequestParam("pageNo") Integer pageNo,@RequestParam("pageSize") Integer pageSize) {
        if(pageNo == null || pageNo < 1) pageNo = 1;
        if(pageSize == null || pageSize < 1) pageSize = 10;

        ResponseUtils response = null;
        try {
            IPage<Map> mapIPage = bookService.selectBookMap(pageNo, pageSize);
            response = new ResponseUtils().put("data", mapIPage);
        }catch (Exception e){
            e.printStackTrace();
            response = new ResponseUtils().put("error",e.getMessage());
        }
        return response;
    }

    @PostMapping("/upload")
    public Map upload(@RequestParam("img") MultipartFile file, HttpServletRequest request) throws IOException {
        String uploadPath = request.getServletContext().getResource("/").getPath() + "/upload/";
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        file.transferTo(new File(uploadPath+fileName+suffix));
        Map map = new LinkedHashMap();
        map.put("msg","success");
        return map;
    }

    @PostMapping("/create")
    public ResponseUtils createBook(Book book) {
        ResponseUtils response = null;
        try {
            book.setEvaluationScore(0f);
            book.setEvaluationQuantity(0);
            bookService.createBook(book);
            response = new ResponseUtils().put("message","success");
        }catch (Exception e){
            e.printStackTrace();
            response = new ResponseUtils().put("error",e.getMessage());
        }
        return response;
    }


    @PostMapping("/update")
    public ResponseUtils updateBook(Book book){
        ResponseUtils resp ;
        try {
            System.out.println(book.getDescription());
            Document doc = Jsoup.parse(book.getDescription());
            Elements elements = doc.select("img");
            if (elements.size() == 0) {
                resp = new ResponseUtils("ImageNotFoundError", "图书描述未包含封面图片");
                return resp;
            }
            String cover = elements.first().attr("src");
            Book b = bookService.selectBookById(book.getBookId());
            b.setBookName(book.getBookName());
            b.setSubTitle(book.getSubTitle());
            b.setAuthor(book.getAuthor());
            b.setCategoryId(book.getCategoryId());
            b.setDescription(book.getDescription());
            b.setCover(cover);
            bookService.updateBook(b);
            resp = new ResponseUtils().put("book",b);
        }catch (Exception e){
            e.printStackTrace();
            resp = new ResponseUtils(e.getClass().getSimpleName(), e.getMessage());
        }
        return resp;
    }

    @PostMapping("/delete")
    public ResponseUtils deleteBook(Long bookId){
        ResponseUtils resp = null;
        try {
            bookService.deleteBook(bookId);
            resp = new ResponseUtils();
        }catch (Exception ex){
            ex.printStackTrace();
            resp = new ResponseUtils(ex.getClass().getSimpleName() , ex.getMessage());
        }
        return resp;
    }
}


